package com.itheima.filter;

import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.logging.LogRecord;
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1/获取请求路径
        HttpServletRequest  request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //2.判断路径是否是登录，如果包含login是登录操作，放行
        String requestURI = request.getRequestURI();
        if(requestURI.contains("login")){
            log.info("登录操作");
            filterChain.doFilter(request,response);
            return;
        }


        //3.获取请求头中token
        String token=request.getHeader("token");

        //4.判断token是否为存在，不存在返回错误状态吗（401）
        if(token==null||token.isEmpty()){
            log.info("令牌为空");
            response.setStatus(401);
            return;
        }

        //5.如果token存在，则校验token是否正确，不正确返回错误状态吗（401）
        try{
            Claims claims =JwtUtils.parseToken(token);
            Integer empId=Integer.valueOf( claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);
            log.info("当前用户id为：{},将其存入ThreadLocal",empId);
        }catch(Exception e){
            log.info("令牌错误");
            response.setStatus(401);
            return;
        }


        //6.如果token正确，则放行
        log.info("令牌正确");
        filterChain.doFilter(request,response);

        CurrentHolder.remove();
    }
}
